#pragma once
#include <iostream>
#include <string>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <functional>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "nocopy.hpp"
#include "Log.hpp"
#include "Comm.hpp"
#include "InetAddr.hpp"

const static std::string defaultip = "0.0.0.0";
const static uint16_t defaultport = 8888;
const static int defaultbuffersize = 1024;
const static int defaultfd = -1;

using task_t = std::function<std::string(std::string)>;

class UdpServer : public nocopy
{
public:
    UdpServer(task_t route, uint16_t port = defaultport)
        : _port(port), _socketfd(defaultfd), _route(route)
    {
    }
    void Init()
    {
        // 创建socket ，就是创建了文件细节
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_socketfd < 0)
        {
            lg(Fatal, " create socket Fail ! , errno : %d , errorstr : %s", errno, strerror(errno));
            exit(Socket_Err);
        }

        lg(Info, "socket create success ! sockfd : %d", _socketfd);
        // bind绑定，绑定网络信息
        struct sockaddr_in local;
        bzero(&local, sizeof(local)); // memset
        // memset(&local,0,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY; // 本机任意ip即可
        // addr.sin_addr.s_addr = inet_addr(_ip.c_str()); // 1.32字节 2.网络字节序
        local.sin_port = htons(_port);

        // int n = bind(_socketfd, (struct sockaddr*)&local, sizeof(local));
        int n = ::bind(_socketfd, (struct sockaddr *)&local, sizeof(local));
        if (n != 0)
        {
            lg(Fatal, "errno : %d , errorstr : %s", errno, strerror(errno));
            exit(Bind_Err);
        }
    }
    void Start()
    {
        // 服务器启动时是一直不退出的
        char buffer[defaultbuffersize];
        while (true)
        {
            // 接收消息的时候
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            // 在网络中收消息
            // ssize_t n = recvfrom(_socketfd, buffer, sizeof(buffer) - 1, 0 , (struct sockaddr*)&client, &len);
            ssize_t n = recvfrom(_socketfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&client, &len);
            if (n > 0)
            {
                InetAddr IA(client);
                buffer[n] = 0;

                std::string response = _route(buffer);
                // std::cout << "[" << IA.ToString() << "] "<< buffer << std::endl;
                std::cout << "[" << IA.ToString() << "] " << response << std::endl;

                sendto(_socketfd, response.c_str() , response.size() , 0, (struct sockaddr *)&client, len);
            }
        }
    }
    ~UdpServer()
    {
    }

private:
    // std::string _ip; // ip32字节
    uint16_t _port; // 端口2字节
    int _socketfd;
    task_t _route; // 设置一个回调，处理消息
};
